using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace MoEngine
{
	public class Animation : Graph2D
	{
		AnimTemplate m_Template;
		float m_Scale;
		int m_Width;
		int m_Height;

		int m_CurrentFrame;

		bool m_bPlaying;
		bool m_bLooping = false;
		float m_DurationToNextFrame;

		public float Scale
		{
			get { return m_Scale; }
			set 
			{
				if (m_Scale != value)
				{
					m_Scale = value;
					m_Width = (int)Math.Round((double)m_Template.Width * m_Scale);
					m_Height = (int)Math.Round((double)m_Template.Height * m_Scale);
				}
			}
		}

		public Animation(AnimTemplate template, bool bAutoStart)
		{
			m_Template = template;
			Scale = 1;
			Reset();
			m_bPlaying = bAutoStart;
		}

		public Animation(AnimTemplate template)
			: this(template, true)
		{

		}


		public void Play()
		{
			m_bPlaying = true;
		}

		public void Stop()
		{
			Reset();
			m_bPlaying = false;
		}

		protected void Reset()
		{
			m_CurrentFrame = 0;
			m_DurationToNextFrame = m_Template.Interval;
		}

		protected override void Update(GameTime gameTime)
		{
			if (m_bPlaying)
			{
				float totalTimePassed = (float)gameTime.ElapsedGameTime.TotalSeconds;

				while (totalTimePassed > 0.0f)
				{
					if (totalTimePassed >= m_DurationToNextFrame)
					{
						totalTimePassed -= m_DurationToNextFrame;

						// next frame
						m_CurrentFrame += 1;
						if (m_CurrentFrame >= m_Template.FrameCount)
						{
							if (!m_bLooping)
							{
								Stop();
								Parent.Detach(this);
								break;
							}
							m_CurrentFrame = 0;
						}
						m_DurationToNextFrame = m_Template.Interval;

					}
					else
					{
						m_DurationToNextFrame -= totalTimePassed;
						totalTimePassed = 0.0f;
						break;
					}
				}
			}

			base.Update(gameTime);
		}

		protected override void Render(Camera2D camera, SpriteBatch spriteBatch)
		{
			Rectangle rect = new Rectangle(
				(int)RealLoction.X - m_Width / 2, 
				(int)RealLoction.Y - m_Height / 2,
				m_Width, m_Height);
			
			m_Template.Render(spriteBatch, rect, m_CurrentFrame);
		}
	}
}
